import cv2
import multiprocessing
import time

list = [
   "rtsp://admin:1qaz2wsx@60.12.233.54:5018/h264/ch1/main/av_stream",
   "rtsp://admin:1qaz2wsx@60.12.233.54:5017/h264/ch1/main/av_stream",
   "rtsp://admin:1qaz2wsx@60.12.233.54:5016/h264/ch1/main/av_stream",
]

caps = []
for url in list:
    cap = cv2.VideoCapture(url)
    if cap.isOpened():
        caps.append(cap)
    else:
        print("cam {} is not open.".format(url))

imgq = multiprocessing.Queue(10)

def saveimg(imgq):
    print('start save')
    cnt = 0
    while True:
        time.sleep(1)
        # print("size = {}".format(imgq.qsize()))
        if imgq.qsize() > 0:
            # print("try save")
            img = imgq.get()
            cnt += 1
            times = str(time.time())
            cv2.imwrite('./save/{}.png'.format(str(cnt) + times), img)
if __name__ == '__main__':
    proc = multiprocessing.Process(target=saveimg, args=(imgq,))
    proc.start()

    n = -1
    while True:
        n = (n + 1) % (10 * 24)
        for cap in caps:
            cap.grab()
            if n == 0:  # read every 4th frame
                _, img = cap.retrieve()
                try:
                    imgq.put(img, block=False)
                    print('put ome image, {}'.format(imgq.qsize()))
                except:
                    print("too many images to save.")
        time.sleep(0.01)  # wait time

